<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>角色管理系统</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../../js/main.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #e6f0ff, #cce0ff);
            /*min-height: 100vh;*/
        }

        .container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(26, 58, 143, 0.1);
            padding: 25px;
            max-width: 1600px;
            margin: 0 auto;
        }

        .search-bar {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        input[type="text"], select {
            padding: 10px 15px;
            border: 1px solid #c7d8ff;
            border-radius: 5px;
            font-size: 14px;
            transition: all 0.3s;
        }

        input[type="text"]:focus, select:focus {
            border-color: #1a3a8f;
            box-shadow: 0 0 0 3px rgba(26, 58, 143, 0.2);
            outline: none;
        }

        button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }

        .btn-primary {
            background: #1a3a8f;
            color: white;
        }

        .btn-primary:hover {
            background: #0d1b4a;
        }

        .btn-success {
            background: #2d8f1a;
            color: white;
        }

        .btn-success:hover {
            background: #1b4a0d;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 25px 0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #e0ebff;
        }

        th {
            background: #f0f5ff;
            color: #1a3a8f;
            font-weight: 600;
        }

        tr:hover {
            background-color: #f8faff;
        }

        .pagination {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-top: 20px;
        }

        .pagination button {
            padding: 8px 16px;
            background: #f0f5ff;
            color: #1a3a8f;
            border: 1px solid #c7d8ff;
        }

        .pagination button:hover {
            background: #e0ebff;
        }

        .pagination select {
            padding: 8px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .action-buttons button {
            padding: 8px 12px;
            font-size: 13px;
            background: #f0f5ff;
            color: #1a3a8f;
            border: 1px solid #c7d8ff;
        }

        .action-buttons button:hover {
            background: #e0ebff;
        }

        /* 菜单对话框样式 */
        .menu-dialog {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .menu-dialog-content {
            background: white;
            padding: 25px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
        }

        .menu-dialog-content h3 {
            color: #1a3a8f;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e0ebff;
        }

        .menu-item {
            /*margin-bottom: 15px;*/
        }

        .menu-item label {
            display: flex;
            align-items: center;
            cursor: pointer;
            color: #333;
        }

        .menu-item input[type="checkbox"] {
            margin-right: 10px;
            width: 16px;
            height: 16px;
            accent-color: #1a3a8f;
        }

        .sub-menu {
            margin-left: 25px;
            margin-top: 10px;
        }

        .dialog-buttons {
            display: flex;
            justify-content: flex-end;
            margin-top: 25px;
            gap: 15px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .search-bar {
                flex-direction: column;
            }

            .action-buttons {
                flex-direction: column;
            }

            .menu-dialog-content {
                width: 95%;
                padding: 15px;
            }
        }
    </style>
</head>
<body>
<!-- 添加分页查询界面 -->
<div class="container">
    <div class="search-bar">
        <input type="text" id="searchInput" placeholder="角色名称..." style="flex:1">
        <button class="btn-primary" onclick="loadRoles()">查询</button>
        <button class="btn-success" onclick="showAddDialog()">新建角色</button>
    </div>

    <table>
        <thead>
        <tr>
            <th style="width: 120px;">角色ID</th>
            <th>角色名称</th>
            <th>角色描述</th>
            <th style="width: 400px;">操作</th>
        </tr>
        </thead>
        <tbody id="dataTable"></tbody>
    </table>

    <div class="pagination">
        <button onclick="prevPage()">上一页</button>
        <span id="pageInfo">第1页/共1页</span>
        <button onclick="nextPage()">下一页</button>
        每页显示：
        <select id="pageSize" onchange="loadRoles()">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
        </select>
    </div>
</div>

<!-- 菜单分配对话框 -->
<div class="menu-dialog" id="menuDialog">
    <div class="menu-dialog-content">
        <h3>菜单权限分配</h3>
        <div id="menuTree"></div>
        <div class="dialog-buttons">
            <button class="btn-primary" onclick="saveRoleMenus()">保存</button>
            <button onclick="closeMenuDialog()">取消</button>
        </div>
    </div>
</div>

<script>
    currentPage = 1;
    totalPages = 1;
    currentRoleId = null; // 当前正在分配菜单的角色ID
    allMenus = []; // 所有菜单数据
    selectedMenuIds = []; // 已选中的菜单ID

    function loadRoles() {
        $.ajax({
            url: '/sysRole/pageRole',
            type: 'GET',
            data: {
                roleName: $('#searchInput').val(),
                current: currentPage,
                size: $('#pageSize').val()
            },
            success: function(response) {
                let tbody = $('#dataTable').empty();
                response.records.forEach(role => {
                    tbody.append(`
                        <tr>
                            <td>${role.roleId}</td>
                            <td>${role.roleName}</td>
                            <td>${role.description || ''}</td>
                            <td class="action-buttons">
                                <button onclick="editRole(${role.roleId}, '${role.roleName}', '${role.description || ''}')">编辑</button>
                                <button onclick="deleteRole(${role.roleId})">删除</button>
                                <button onclick="showMenuDialog(${role.roleId})">菜单管理</button>
                            </td>
                        </tr>
                    `);
                });

                // 更新分页信息
                totalPages = response.pages;
                $('#pageInfo').text(`第${response.current}页/共${totalPages}页`);
            }
        });
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            loadRoles();
        }
    }

    function nextPage() {
        if (currentPage < totalPages) {
            currentPage++;
            loadRoles();
        }
    }

    // 初始化加载数据
    loadRoles();

    function deleteRole(roleId) {
        if (confirm('确定要删除该角色吗？')) {
            $.ajax({
                url: `/sysRole/deleteRole/${roleId}`,
                type: 'DELETE',
                success: () => {
                    alert('删除成功');
                    loadRoles(); // 刷新列表
                },
                error: () => alert('删除失败')
            });
        }
    }

    // 新增编辑功能
    function editRole(roleId, oldName, oldDesc) {
        const newName = prompt('请输入新角色名称', oldName);
        const newDesc = prompt('请输入新描述', oldDesc);

        if (newName !== null) {
            $.ajax({
                url: '/sysRole/updateRole',
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify({
                    roleId: roleId,
                    roleName: newName,
                    description: newDesc
                }),
                success: () => {
                    alert('修改成功');
                    loadRoles(); // 刷新列表
                },
                error: () => alert('修改失败')
            });
        }
    }

    function showAddDialog() {
        const roleName = prompt('请输入角色名称');
        if (!roleName) return;

        const description = prompt('请输入角色描述');

        $.ajax({
            url: '/sysRole/addRole',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                roleName: roleName,
                description: description
            }),
            success: () => {
                alert('添加成功');
                loadRoles(); // 刷新列表
            },
            error: () => alert('添加失败')
        });
    }

    // 显示菜单分配对话框
    function showMenuDialog(roleId) {
        currentRoleId = roleId;
        $('#menuDialog').css('display', 'flex');

        // 加载所有菜单
        $.ajax({
            url: '/sysMenu/getAllMenu',
            type: 'GET',
            success: function(response) {
                allMenus = response.data;
                renderMenuTree();

                // 加载角色已有菜单
                loadRoleMenus(roleId);
            },
            error: () => alert('加载菜单失败')
        });
    }

    // 关闭菜单对话框
    function closeMenuDialog() {
        $('#menuDialog').hide();
        currentRoleId = null;
        selectedMenuIds = [];
    }

    // 渲染菜单树
    function renderMenuTree() {
        const menuTree = $('#menuTree').empty();

        // 先找出所有父菜单
        const parentMenus = allMenus.filter(menu => menu.parentId === 0);

        parentMenus.forEach(parentMenu => {
            // 找出所有子菜单
            const childMenus = allMenus.filter(menu => menu.parentId === parentMenu.menuId);

            const parentItem = $(`
                <div class="menu-item">
                    <label>
                        <input type="checkbox" class="parent-menu" data-id="${parentMenu.menuId}">
                        ${parentMenu.menuName}
                    </label>
                    <div class="sub-menu" id="sub-menu-${parentMenu.menuId}"></div>
                </div>
            `);

            menuTree.append(parentItem);

            // 添加子菜单
            const subMenuContainer = $(`#sub-menu-${parentMenu.menuId}`);
            childMenus.forEach(childMenu => {
                subMenuContainer.append(`
                    <div class="menu-item">
                        <label>
                            <input type="checkbox" class="child-menu" data-id="${childMenu.menuId}" data-parent="${parentMenu.menuId}">
                            ${childMenu.menuName}
                        </label>
                    </div>
                `);
            });

            // 父菜单点击事件 - 全选/取消全选子菜单
            parentItem.find('.parent-menu').change(function() {
                const isChecked = $(this).prop('checked');
                $(this).closest('.menu-item').find('.child-menu').prop('checked', isChecked);

                updateSelectedMenuIds();
            });

            // 子菜单点击事件 - 如果所有子菜单都选中，则选中父菜单；如果有子菜单未选中，则取消父菜单选中
            subMenuContainer.find('.child-menu').change(function() {
                const parentId = $(this).data('parent');
                const parentCheckbox = $(`.parent-menu[data-id="${parentId}"]`);

                const allChecked = $(`.child-menu[data-parent="${parentId}"]:not(:checked)`).length === 0;
                parentCheckbox.prop('checked', allChecked);

                updateSelectedMenuIds();
            });
        });
    }

    // 加载角色已有菜单
    function loadRoleMenus(roleId) {
        $.ajax({
            url: `/sysRoleMenu/getByRoleId/${roleId}`,
            type: 'GET',
            success: function(response) {
                // 清除之前的选择
                $('input[type="checkbox"]').prop('checked', false);
                selectedMenuIds = [];

                if (response.code === 200 && response.data && response.data.length > 0) {
                    // 假设返回的是菜单ID数组
                    selectedMenuIds = response.data.map(id => parseInt(id));

                    // 先处理子菜单
                    selectedMenuIds.forEach(menuId => {
                        const menu = allMenus.find(m => m.menuId === menuId);
                        if (menu) {
                            // 勾选对应的复选框
                            $(`input[data-id="${menuId}"]`).prop('checked', true);

                            // 如果是子菜单，检查其父菜单是否需要选中
                            if (menu.parentId !== 0) {
                                checkParentMenu(menu.parentId);
                            }
                        }
                    });
                }
            },
            error: () => console.log('加载角色菜单失败')
        });
    }

    // 检查并选中父菜单（如果所有子菜单都被选中）
    function checkParentMenu(parentId) {
        // 获取该父菜单下的所有子菜单
        const childMenus = allMenus.filter(m => m.parentId === parentId);

        // 检查这些子菜单是否都在selectedMenuIds中
        const allChildSelected = childMenus.every(child =>
            selectedMenuIds.includes(child.menuId)
        );

        // 如果所有子菜单都被选中，则选中父菜单
        if (allChildSelected && !selectedMenuIds.includes(parentId)) {
            selectedMenuIds.push(parentId);
            $(`input[data-id="${parentId}"]`).prop('checked', true);

            // 递归检查父菜单的父菜单
            const parentMenu = allMenus.find(m => m.menuId === parentId);
            if (parentMenu && parentMenu.parentId !== 0) {
                checkParentMenu(parentMenu.parentId);
            }
        }
    }

    // 更新选中的菜单ID数组
    function updateSelectedMenuIds() {
        selectedMenuIds = [];
        $('input[type="checkbox"]:checked').each(function() {
            selectedMenuIds.push(parseInt($(this).data('id')));
        });
    }

    // 保存角色菜单
    function saveRoleMenus() {
        if (!currentRoleId) return;

        $.ajax({
            url: '/sysRoleMenu/assignMenus',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                roleId: currentRoleId,
                menuIds: selectedMenuIds
            }),
            success: () => {
                alert('保存成功');
                closeMenuDialog();
            },
            error: () => alert('保存失败')
        });
    }
</script>
</body>
</html>